package com.version.manager.service;

import com.version.manager.config.TedisCacheManager;
import com.version.manager.entity.Role;
import com.version.manager.mapper.RoleMapper;
import com.version.manager.model.Msg;
import com.version.manager.model.RoleMenu;
import com.version.manager.util.JWTUtil;
import com.version.manager.util.RedisUtil;
import com.version.manager.vo.JwtAuthenticationRequest;
import io.swagger.models.auth.In;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.slf4j.Logger;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

@Service
@Transactional(rollbackFor = Exception.class)
public class RoleService extends BaseService<RoleMapper,Role> {
    @Resource
    private RoleMapper roleMapper;
    @Resource
    private MenuService menuService;

    @Resource
    private RedisUtil redisUtil;

    private Log log= LogFactory.getLog(RoleService.class);

    public List<Role> getRoleByUser(Integer userId){
        return roleMapper.getRoleByUser(userId);
    }
    public Msg addRole(HttpServletRequest request,RoleMenu roleMenu)throws Exception{
        try{
            Integer companyId=Integer.parseInt(request.getHeader("companyId"));
            Role role=roleMenu.getRole();
            role.setCompanyId(companyId);
            Msg msg= super.saveOrUpdate(role);
            if(msg.getData()!=null){
                role.setId(msg.getData().toString());
            }
            String key="menu::role_menu_"+role.getId();
            menuService.deleteRoleMenu(role);
            menuService.addRoleMenu(role,roleMenu.getMenuIds());
            redisUtil.del(new String[]{key});
            redisUtil.del(new String[]{"MenuTree1::MenuTree1"});

            return Msg.success();
        }catch (Exception ex){
            log.error("保存角色失败:"+ex.getMessage());
            return Msg.fail().addMessage("保存失败");
        }
    }



    public Msg saveOrUpdate(HttpServletRequest request, Role role) throws Exception {
        String companyId=request.getHeader("companyId");
        role.setCompanyId(Integer.parseInt(companyId));
        return super.saveOrUpdate(role);
    }
}
